<template>
	<view class="reaction-container">
		<!-- 测试说明阶段 -->
		<view class="instruction-stage" v-if="currentStage === 'instruction'">
			<view class="header">
				<text class="title">反应时间测试</text>
				<text class="subtitle">测试你的反应速度和注意力</text>
			</view>
			
			<view class="instruction-content">
				<view class="instruction-item">
					<view class="step-number">1</view>
					<text class="step-text">屏幕变红时请等待</text>
				</view>
				<view class="instruction-item">
					<view class="step-number">2</view>
					<text class="step-text">屏幕变绿时立即点击</text>
				</view>
				<view class="instruction-item">
					<view class="step-number">3</view>
					<text class="step-text">完成5轮测试</text>
				</view>
			</view>
			
			<view class="stats-preview">
				<view class="stat-item">
					<text class="stat-label">最佳成绩</text>
					<text class="stat-value">{{ bestTime || '--' }}ms</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">平均成绩</text>
					<text class="stat-value">{{ averageTime || '--' }}ms</text>
				</view>
				<view class="stat-item">
					<text class="stat-label">测试次数</text>
					<text class="stat-value">{{ testCount }}次</text>
				</view>
			</view>
			
			<button class="start-btn" @click="startTest">开始测试</button>
		</view>
		
		<!-- 准备阶段 -->
		<view class="ready-stage" v-if="currentStage === 'ready'">
			<view class="ready-content">
				<text class="ready-text">准备开始</text>
				<text class="ready-subtitle">第 {{ currentRound }}/{{ totalRounds }} 轮</text>
				<view class="countdown">{{ countdown }}</view>
			</view>
		</view>
		
		<!-- 等待阶段 -->
		<view class="wait-stage" v-if="currentStage === 'wait'" @click="handleEarlyClick">
			<view class="wait-content">
				<text class="wait-text">等待绿色出现...</text>
				<text class="wait-subtitle">不要提前点击</text>
				<view class="pulse-circle"></view>
			</view>
		</view>
		
		<!-- 点击阶段 -->
		<view class="click-stage" v-if="currentStage === 'click'" @click="handleClick">
			<view class="click-content">
				<text class="click-text">点击！</text>
				<text class="click-subtitle">立即点击屏幕</text>
				<view class="click-indicator">⚡</view>
			</view>
		</view>
		
		<!-- 结果显示阶段 -->
		<view class="result-stage" v-if="currentStage === 'result'">
			<view class="result-content">
				<view class="result-header">
					<text class="result-title">第 {{ currentRound }} 轮结果</text>
					<text class="result-time" :class="getResultClass(currentResult)">{{ currentResult }}ms</text>
				</view>
				
				<view class="result-feedback">
					<text class="feedback-text">{{ getFeedbackText(currentResult) }}</text>
					<text class="feedback-emoji">{{ getFeedbackEmoji(currentResult) }}</text>
				</view>
				
				<view class="progress-info">
					<text class="progress-text">进度: {{ currentRound }}/{{ totalRounds }}</text>
					<view class="progress-bar">
						<view class="progress-fill" :style="{ width: (currentRound / totalRounds * 100) + '%' }"></view>
					</view>
				</view>
				
				<button class="continue-btn" @click="nextRound" v-if="currentRound < totalRounds">下一轮</button>
				<button class="finish-btn" @click="showFinalResult" v-else>查看总结果</button>
			</view>
		</view>
		
		<!-- 最终结果阶段 -->
		<view class="final-result-stage" v-if="currentStage === 'final'">
			<view class="final-header">
				<text class="final-title">测试完成</text>
				<text class="final-subtitle">反应时间测试结果</text>
			</view>
			
			<view class="final-stats">
				<view class="main-stat">
					<text class="main-label">平均反应时间</text>
					<text class="main-value">{{ finalAverage }}ms</text>
					<text class="main-level">{{ getPerformanceLevel(finalAverage) }}</text>
				</view>
				
				<view class="detail-stats">
					<view class="detail-item">
						<text class="detail-label">最快时间</text>
						<text class="detail-value">{{ Math.min(...testResults) }}ms</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">最慢时间</text>
						<text class="detail-value">{{ Math.max(...testResults) }}ms</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">稳定性</text>
						<text class="detail-value">{{ getStabilityText() }}</text>
					</view>
				</view>
			</view>
			
			<view class="results-list">
				<text class="list-title">各轮成绩</text>
				<view class="result-item" v-for="(result, index) in testResults" :key="index">
					<text class="round-number">第{{ index + 1 }}轮</text>
					<text class="round-result" :class="getResultClass(result)">{{ result }}ms</text>
					<text class="round-rank">{{ getRankText(result) }}</text>
				</view>
			</view>
			
			<view class="action-buttons">
				<button class="retry-btn" @click="resetTest">重新测试</button>
				<button class="home-btn" @click="goHome">返回首页</button>
			</view>
		</view>
		
		<!-- 错误提示 -->
		<view class="error-stage" v-if="currentStage === 'error'">
			<view class="error-content">
				<text class="error-title">提前点击了！</text>
				<text class="error-subtitle">请等待绿色出现再点击</text>
				<view class="error-icon">❌</view>
				<button class="retry-round-btn" @click="retryRound">重试本轮</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'

// 测试状态
const currentStage = ref('instruction') // instruction, ready, wait, click, result, final, error
const currentRound = ref(1)
const totalRounds = ref(5)
const countdown = ref(3)
const testResults = ref([])
const currentResult = ref(0)
const startTime = ref(0)
const waitTimer = ref(null)
const countdownTimer = ref(null)

// 历史数据
const bestTime = ref(null)
const averageTime = ref(null)
const testCount = ref(0)

// 计算属性
const finalAverage = computed(() => {
	if (testResults.value.length === 0) return 0
	return Math.round(testResults.value.reduce((sum, time) => sum + time, 0) / testResults.value.length)
})

// 页面加载时获取历史数据
onMounted(() => {
	loadHistoryData()
})

// 页面卸载时清理定时器
onUnmounted(() => {
	clearAllTimers()
})

// 加载历史数据
const loadHistoryData = () => {
	try {
		const history = uni.getStorageSync('reactionHistory')
		if (history) {
			bestTime.value = history.bestTime
			averageTime.value = history.averageTime
			testCount.value = history.testCount || 0
		}
	} catch (e) {
		console.error('加载历史数据失败:', e)
	}
}

// 保存测试结果
const saveTestResult = () => {
	try {
		const history = uni.getStorageSync('reactionHistory') || []
		
		// 创建新的测试记录
		const newRecord = {
			averageTime: finalAverage.value,
			bestTime: Math.min(...testResults.value),
			worstTime: Math.max(...testResults.value),
			testResults: [...testResults.value],
			timestamp: new Date().toISOString(),
			date: new Date().toLocaleDateString('zh-CN')
		}
		
		// 添加到历史记录
		history.push(newRecord)
		
		// 保持最近50条记录
		if (history.length > 50) {
			history.shift()
		}
		
		uni.setStorageSync('reactionHistory', history)
		
		// 触发成就系统检查
		triggerAchievementCheck()
		
		// 更新当前显示的数据
		const allBestTimes = history.map(record => record.bestTime)
		bestTime.value = Math.min(...allBestTimes)
		averageTime.value = Math.round(history.reduce((sum, record) => sum + record.averageTime, 0) / history.length)
		testCount.value = history.length
	} catch (e) {
		console.error('保存测试结果失败:', e)
	}
}

// 触发成就系统检查
const triggerAchievementCheck = () => {
	try {
		// 检查反应时间成就
		const bestReactionTime = Math.min(...testResults.value)
		if (bestReactionTime < 250) {
			// 可以通过全局事件或直接调用profile页面的成就检查函数
			// 这里我们通过本地存储来触发
			const achievementTrigger = {
				type: 'reaction_time',
				value: bestReactionTime,
				timestamp: new Date().toISOString()
			}
			uni.setStorageSync('achievementTrigger', achievementTrigger)
		}
		
		// 检查测试完成成就
		const testCompleteTrigger = {
			type: 'test_completed',
			value: 1,
			timestamp: new Date().toISOString()
		}
		uni.setStorageSync('testCompleteTrigger', testCompleteTrigger)
		
		// 检查完美分数成就
		if (finalAverage.value < 200) {
			const perfectTrigger = {
				type: 'perfect_score',
				value: 1,
				timestamp: new Date().toISOString()
			}
			uni.setStorageSync('perfectScoreTrigger', perfectTrigger)
		}
		
		// 检查时间相关成就
		const currentHour = new Date().getHours()
		if (currentHour >= 22 || currentHour <= 6) {
			const nightTrigger = {
				type: 'night_test',
				value: 1,
				timestamp: new Date().toISOString()
			}
			uni.setStorageSync('nightTestTrigger', nightTrigger)
		} else if (currentHour >= 5 && currentHour <= 8) {
			const earlyTrigger = {
				type: 'early_test',
				value: 1,
				timestamp: new Date().toISOString()
			}
			uni.setStorageSync('earlyTestTrigger', earlyTrigger)
		}
	} catch (e) {
		console.error('触发成就检查失败:', e)
	}
}

// 清理所有定时器
const clearAllTimers = () => {
	if (waitTimer.value) {
		clearTimeout(waitTimer.value)
		waitTimer.value = null
	}
	if (countdownTimer.value) {
		clearInterval(countdownTimer.value)
		countdownTimer.value = null
	}
}

// 开始测试
const startTest = () => {
	currentStage.value = 'ready'
	currentRound.value = 1
	testResults.value = []
	startCountdown()
}

// 开始倒计时
const startCountdown = () => {
	countdown.value = 3
	countdownTimer.value = setInterval(() => {
		countdown.value--
		if (countdown.value <= 0) {
			clearInterval(countdownTimer.value)
			startWaitStage()
		}
	}, 1000)
}

// 开始等待阶段
const startWaitStage = () => {
	currentStage.value = 'wait'
	// 随机等待时间 2-6秒
	const waitTime = Math.random() * 4000 + 2000
	waitTimer.value = setTimeout(() => {
		startClickStage()
	}, waitTime)
}

// 开始点击阶段
const startClickStage = () => {
	currentStage.value = 'click'
	startTime.value = Date.now()
}

// 处理提前点击
const handleEarlyClick = () => {
	clearAllTimers()
	currentStage.value = 'error'
}

// 处理正确点击
const handleClick = () => {
	const reactionTime = Date.now() - startTime.value
	currentResult.value = reactionTime
	testResults.value.push(reactionTime)
	currentStage.value = 'result'
}

// 下一轮
const nextRound = () => {
	currentRound.value++
	currentStage.value = 'ready'
	startCountdown()
}

// 重试当前轮
const retryRound = () => {
	currentStage.value = 'ready'
	startCountdown()
}

// 显示最终结果
const showFinalResult = () => {
	currentStage.value = 'final'
	saveTestResult()
}

// 重置测试
const resetTest = () => {
	clearAllTimers()
	currentStage.value = 'instruction'
	currentRound.value = 1
	testResults.value = []
	currentResult.value = 0
}

// 返回首页
const goHome = () => {
	uni.navigateBack()
}

// 获取结果样式类
const getResultClass = (time) => {
	if (time < 200) return 'excellent'
	if (time < 300) return 'good'
	if (time < 400) return 'average'
	return 'slow'
}

// 获取反馈文本
const getFeedbackText = (time) => {
	if (time < 200) return '反应神速！'
	if (time < 300) return '反应很快！'
	if (time < 400) return '反应正常'
	return '还需加油'
}

// 获取反馈表情
const getFeedbackEmoji = (time) => {
	if (time < 200) return '🚀'
	if (time < 300) return '⚡'
	if (time < 400) return '👍'
	return '💪'
}

// 获取性能等级
const getPerformanceLevel = (avgTime) => {
	if (avgTime < 200) return '优秀'
	if (avgTime < 300) return '良好'
	if (avgTime < 400) return '一般'
	return '需要提升'
}

// 获取稳定性文本
const getStabilityText = () => {
	if (testResults.value.length < 2) return '无法计算'
	const max = Math.max(...testResults.value)
	const min = Math.min(...testResults.value)
	const diff = max - min
	if (diff < 50) return '非常稳定'
	if (diff < 100) return '比较稳定'
	if (diff < 200) return '一般稳定'
	return '不够稳定'
}

// 获取排名文本
const getRankText = (time) => {
	if (time < 200) return '顶尖'
	if (time < 250) return '优秀'
	if (time < 300) return '良好'
	if (time < 400) return '一般'
	return '待提升'
}
</script>

<style lang="scss" scoped>
.reaction-container {
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	position: relative;
}

// 说明阶段样式
.instruction-stage {
	flex: 1;
	padding: 40rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
	display: flex;
	flex-direction: column;

	.header {
		text-align: center;
		margin-bottom: 60rpx;
		
		.title {
			font-size: 48rpx;
			font-weight: bold;
			display: block;
			margin-bottom: 16rpx;
		}
		
		.subtitle {
			font-size: 28rpx;
			opacity: 0.9;
			display: block;
		}
	}
	
	.instruction-content {
		margin-bottom: 60rpx;
		
		.instruction-item {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;
			
			.step-number {
				width: 60rpx;
				height: 60rpx;
				border-radius: 30rpx;
				background: rgba(255, 255, 255, 0.2);
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				font-weight: bold;
				margin-right: 30rpx;
			}
			
			.step-text {
				font-size: 30rpx;
			}
		}
	}
	
	.stats-preview {
		display: flex;
		justify-content: space-around;
		margin-bottom: 60rpx;
		
		.stat-item {
			text-align: center;
			
			.stat-label {
				font-size: 24rpx;
				opacity: 0.8;
				display: block;
				margin-bottom: 8rpx;
			}
			
			.stat-value {
				font-size: 32rpx;
				font-weight: bold;
				display: block;
			}
		}
	}
	
	.start-btn {
		width: 100%;
		height: 100rpx;
		background: rgba(255, 255, 255, 0.2);
		border: 2rpx solid rgba(255, 255, 255, 0.3);
		border-radius: 50rpx;
		color: white;
		font-size: 32rpx;
		font-weight: bold;
		margin-top: auto;
		
		&:active {
			opacity: 0.8;
		}
	}
}

// 准备阶段样式
.ready-stage {
	flex: 1;
	background: #4CAF50;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	
	.ready-content {
		text-align: center;
		
		.ready-text {
			font-size: 48rpx;
			font-weight: bold;
			display: block;
			margin-bottom: 20rpx;
		}
		
		.ready-subtitle {
			font-size: 28rpx;
			opacity: 0.9;
			display: block;
			margin-bottom: 40rpx;
		}
		
		.countdown {
			font-size: 120rpx;
			font-weight: bold;
			animation: pulse 1s infinite;
		}
	}
}

// 等待阶段样式
.wait-stage {
	flex: 1;
	background: #f44336;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	cursor: pointer;
	
	.wait-content {
		text-align: center;
		
		.wait-text {
			font-size: 48rpx;
			font-weight: bold;
			display: block;
			margin-bottom: 20rpx;
		}
		
		.wait-subtitle {
			font-size: 28rpx;
			opacity: 0.9;
			display: block;
			margin-bottom: 40rpx;
		}
		
		.pulse-circle {
			width: 120rpx;
			height: 120rpx;
			border-radius: 60rpx;
			background: rgba(255, 255, 255, 0.3);
			margin: 0 auto;
			animation: pulse 2s infinite;
		}
	}
}

// 点击阶段样式
.click-stage {
	flex: 1;
	background: #4CAF50;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	cursor: pointer;
	animation: flash 0.5s infinite;
	
	.click-content {
		text-align: center;
		
		.click-text {
			font-size: 64rpx;
			font-weight: bold;
			display: block;
			margin-bottom: 20rpx;
		}
		
		.click-subtitle {
			font-size: 32rpx;
			display: block;
			margin-bottom: 40rpx;
		}
		
		.click-indicator {
			font-size: 80rpx;
			animation: bounce 0.5s infinite;
		}
	}
}

// 结果阶段样式
.result-stage {
	flex: 1;
	padding: 40rpx;
	background: white;
	display: flex;
	flex-direction: column;
	justify-content: center;
	
	.result-content {
		text-align: center;
		
		.result-header {
			margin-bottom: 40rpx;
			
			.result-title {
				font-size: 32rpx;
				color: #666;
				display: block;
				margin-bottom: 20rpx;
			}
			
			.result-time {
				font-size: 72rpx;
				font-weight: bold;
				display: block;
				
				&.excellent { color: #4CAF50; }
				&.good { color: #2196F3; }
				&.average { color: #FF9800; }
				&.slow { color: #f44336; }
			}
		}
		
		.result-feedback {
			margin-bottom: 40rpx;
			
			.feedback-text {
				font-size: 36rpx;
				color: #333;
				display: block;
				margin-bottom: 10rpx;
			}
			
			.feedback-emoji {
				font-size: 48rpx;
				display: block;
			}
		}
		
		.progress-info {
			margin-bottom: 40rpx;
			
			.progress-text {
				font-size: 28rpx;
				color: #666;
				display: block;
				margin-bottom: 20rpx;
			}
			
			.progress-bar {
				height: 8rpx;
				background: #f0f0f0;
				border-radius: 4rpx;
				overflow: hidden;
				
				.progress-fill {
					height: 100%;
					background: linear-gradient(90deg, #667eea, #764ba2);
					transition: width 0.3s ease;
				}
			}
		}
		
		.continue-btn, .finish-btn {
			width: 100%;
			height: 80rpx;
			background: linear-gradient(90deg, #667eea, #764ba2);
			color: white;
			border: none;
			border-radius: 40rpx;
			font-size: 32rpx;
			font-weight: bold;
			
			&:active {
				opacity: 0.8;
			}
		}
	}
}

// 最终结果阶段样式
.final-result-stage {
	flex: 1;
	padding: 40rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
	overflow-y: auto;
	
	.final-header {
		text-align: center;
		margin-bottom: 40rpx;
		
		.final-title {
			font-size: 48rpx;
			font-weight: bold;
			display: block;
			margin-bottom: 16rpx;
		}
		
		.final-subtitle {
			font-size: 28rpx;
			opacity: 0.9;
			display: block;
		}
	}
	
	.final-stats {
		margin-bottom: 40rpx;
		
		.main-stat {
			text-align: center;
			margin-bottom: 30rpx;
			padding: 30rpx;
			background: rgba(255, 255, 255, 0.1);
			border-radius: 20rpx;
			
			.main-label {
				font-size: 28rpx;
				opacity: 0.8;
				display: block;
				margin-bottom: 10rpx;
			}
			
			.main-value {
				font-size: 64rpx;
				font-weight: bold;
				display: block;
				margin-bottom: 10rpx;
			}
			
			.main-level {
				font-size: 32rpx;
				display: block;
			}
		}
		
		.detail-stats {
			display: flex;
			justify-content: space-between;
			gap: 20rpx;
			
			.detail-item {
				flex: 1;
				text-align: center;
				padding: 20rpx;
				background: rgba(255, 255, 255, 0.1);
				border-radius: 15rpx;
				
				.detail-label {
					font-size: 22rpx;
					opacity: 0.8;
					display: block;
					margin-bottom: 8rpx;
				}
				
				.detail-value {
					font-size: 28rpx;
					font-weight: bold;
					display: block;
				}
			}
		}
	}
	
	.results-list {
		margin-bottom: 40rpx;
		
		.list-title {
			font-size: 32rpx;
			font-weight: bold;
			display: block;
			margin-bottom: 20rpx;
			text-align: center;
		}
		
		.result-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx;
			margin-bottom: 15rpx;
			background: rgba(255, 255, 255, 0.1);
			border-radius: 15rpx;
			
			.round-number {
				font-size: 28rpx;
			}
			
			.round-result {
				font-size: 32rpx;
				font-weight: bold;
				
				&.excellent { color: #4CAF50; }
				&.good { color: #2196F3; }
				&.average { color: #FF9800; }
				&.slow { color: #f44336; }
			}
			
			.round-rank {
				font-size: 24rpx;
				opacity: 0.8;
			}
		}
	}
	
	.action-buttons {
		display: flex;
		gap: 20rpx;
		
		.retry-btn, .home-btn {
			flex: 1;
			height: 80rpx;
			border: 2rpx solid rgba(255, 255, 255, 0.3);
			border-radius: 40rpx;
			color: white;
			font-size: 28rpx;
			font-weight: bold;
			background: rgba(255, 255, 255, 0.1);
			
			&:active {
				opacity: 0.8;
			}
		}
	}
}

// 错误阶段样式
.error-stage {
	flex: 1;
	background: #f44336;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	
	.error-content {
		text-align: center;
		
		.error-title {
			font-size: 48rpx;
			font-weight: bold;
			display: block;
			margin-bottom: 20rpx;
		}
		
		.error-subtitle {
			font-size: 28rpx;
			opacity: 0.9;
			display: block;
			margin-bottom: 40rpx;
		}
		
		.error-icon {
			font-size: 80rpx;
			margin-bottom: 40rpx;
			display: block;
		}
		
		.retry-round-btn {
			width: 300rpx;
			height: 80rpx;
			background: rgba(255, 255, 255, 0.2);
			border: 2rpx solid rgba(255, 255, 255, 0.3);
			border-radius: 40rpx;
			color: white;
			font-size: 28rpx;
			font-weight: bold;
			
			&:active {
				opacity: 0.8;
			}
		}
	}
}

// 动画效果
@keyframes pulse {
	0%, 100% { transform: scale(1); opacity: 1; }
	50% { transform: scale(1.1); opacity: 0.7; }
}

@keyframes flash {
	0%, 100% { background: #4CAF50; }
	50% { background: #66BB6A; }
}

@keyframes bounce {
	0%, 100% { transform: translateY(0); }
	50% { transform: translateY(-20rpx); }
}
</style>
